'use client';

import {
  type ChangeEvent,
  type Dispatch,
  type FormEvent,
  type SetStateAction,
  useEffect,
  useState,
} from 'react';
import { useMutation } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IConfigEmail, IConfigEmailItem, IDifference } from '@/interfaces';
import type { IConfigEmailContentType } from '@/types';
import { updateEmailConfig } from '@/services/api';
import classNames from 'classnames';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateConfigEmail(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: IConfigEmail;
    translatedFields: PrefixedTTranslatedFields<'configAdminPage'>;
  },
) {
  const [tabIndex, setTabIndex] = useState(0);
  const [conditionsFulfilled, setConditionsFulfilled] = useState(false);
  const { show } = useToast();

  function onClickTab(index: number) {
    if (!conditionsFulfilled && index !== 0) {
      show({
        type: 'WARNING',
        message: translatedFields.config.phone.verifyTip,
      });
      return;
    }
    setTabIndex(index);
  }

  return (
    <Box>
      <div className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.config.email.tip}
          </label>
          <ol>
            <li>
              <span className="me-2">
                {translatedFields.config.email.emailTip}
              </span>
              <a
                target="_blank"
                href="https://console.cloud.tencent.com/ses"
                rel="noreferrer"
              >
                {translatedFields.config.email.tencentCloud}
              </a>
              &nbsp;/&nbsp;
              <a
                target="_blank"
                href="https://dm.console.aliyun.com/#/directmail/Home/cn-hangzhou"
                rel="noreferrer"
              >
                {translatedFields.config.email.aliCloud}
              </a>
            </li>
            <li>{translatedFields.config.email.lengthTip}</li>
            <li>{translatedFields.config.email.exampleTip}</li>
          </ol>
        </div>

        <nav className="nav nav-pills flex-column flex-sm-row">
          <a
            onClick={onClickTab.bind(this, 0)}
            className={classNames(
              'flex-sm-fill text-sm-center nav-link cursor-pointer',
              {
                'bg-light': tabIndex === 0,
              },
            )}
          >
            {translatedFields.config.email.verify}
          </a>
          <a
            onClick={onClickTab.bind(this, 1)}
            className={classNames(
              'flex-sm-fill text-sm-center nav-link cursor-pointer',
              {
                'bg-light': tabIndex === 1,
              },
            )}
          >
            {translatedFields.config.email.login}
          </a>
          <a
            onClick={onClickTab.bind(this, 2)}
            className={classNames(
              'flex-sm-fill text-sm-center nav-link cursor-pointer',
              {
                'bg-light': tabIndex === 2,
              },
            )}
          >
            {translatedFields.config.email.register}
          </a>
        </nav>

        {tabIndex === 0 && (
          <Item
            type="VERIFY"
            source={source}
            translatedFields={translatedFields}
            setConditionsFulfilled={setConditionsFulfilled}
          />
        )}

        {tabIndex === 1 && (
          <Item
            type="LOGIN"
            source={source}
            translatedFields={translatedFields}
          />
        )}

        {tabIndex === 2 && (
          <Item
            type="REGISTER"
            source={source}
            translatedFields={translatedFields}
          />
        )}
      </div>
    </Box>
  );
}

const Item = ({
  type,
  source,
  translatedFields,
  setConditionsFulfilled,
}: {
  type: IConfigEmailContentType;
  source: IConfigEmail;
  translatedFields: PrefixedTTranslatedFields<'configAdminPage'>;
  setConditionsFulfilled?: Dispatch<SetStateAction<boolean>>;
}) => {
  const defaultForm = {
    service: source.list[type]?.service ?? 'TENCENT',
    aliyun: {
      enable: false,
      expire: 'PT5M',
      total: 5,
      interval: 'PT1M',
      recoveryTime: 'PT24H',
      length: 4,
      alphanumeric: false,
      alphabetic: false,
      ascii: false,
      numeric: true,
      accessKeyId: '',
      accessKeySecret: '',
      endpoint: '',
      accountName: '',
      addressType: 0,
      replyToAddress: false,
      subject: '',
      toAddress: '',
      action: '',
      clickTrace: '',
      fromAlias: '',
      htmlBody: '',
      tagName: '',
      textBody: '',
      replyAddress: '',
      replyAddressAlias: '',
      ...(source.list[type]?.aliyun ?? {}),
    },
    tencent: {
      enable: false,
      expire: 'PT5M',
      total: 5,
      interval: 'PT1M',
      recoveryTime: 'PT24H',
      length: 4,
      alphanumeric: false,
      alphabetic: false,
      ascii: false,
      numeric: true,
      secretId: '',
      secretKey: '',
      action: '',
      version: '',
      endpoint: '',
      region: '',
      fromEmailAddress: '',
      destination: [],
      subject: '',
      replyToAddresses: '',
      template: {
        templateId: 1,
        templateData: '',
      },
      simple: '',
      attachments: '',
      unsubscribe: '',
      triggerType: 0,
      ...(source.list[type]?.tencent ?? {}),
    },
  };
  const { show } = useToast();
  const [form, setForm] = useState<IConfigEmailItem>(defaultForm);
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [subTabIndex, setSubTabIndex] = useState(1);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateEmailConfigMutation = useMutation(updateEmailConfig);

  useEffect(() => {
    const diffData = diff(defaultForm, form);
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source, type]);
  useEffect(() => {
    if (typeof setConditionsFulfilled === 'function') {
      let _value = false;
      if (form.service === 'TENCENT') {
        _value = form.tencent.enable;
      } else if (form.service === 'ALIYUN') {
        _value = form.aliyun.enable;
      }
      setConditionsFulfilled(_value);
    }
  }, [
    form.aliyun.enable,
    form.service,
    form.tencent.enable,
    setConditionsFulfilled,
  ]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData);
      await updateEmailConfigMutation.mutateAsync({
        data: {
          list: {
            [type]: data,
          },
        },
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateEmailConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onClickSubTab(index: number) {
    setSubTabIndex(index);
  }

  function onChangeForm(
    e: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;
    const itemName = subTabIndex === 1 ? 'tencent' : 'aliyun';

    if (name === 'service') {
      setForm({
        ...form,
        service: value as any,
      });
    } else if (
      name === 'enable' ||
      name === 'alphanumeric' ||
      name === 'alphabetic' ||
      name === 'ascii' ||
      name === 'numeric'
    ) {
      setForm({
        ...form,
        [itemName]: {
          ...form[itemName],
          [name]: value === 'true',
        },
      });
    } else if (name === 'total' || name === 'length') {
      setForm({
        ...form,
        [itemName]: {
          ...form[itemName],
          [name]: parseInt(value),
        },
      });
    } else if (name === 'templateId') {
      setForm({
        ...form,
        tencent: {
          ...form.tencent,
          template: {
            ...form.tencent.template,
            templateId: parseInt(value),
          },
        },
      });
    } else {
      setForm({
        ...form,
        [itemName]: {
          ...form[itemName],
          [name]: value,
        },
      });
    }
  }

  return (
    <div className="vstack gap-4">
      <nav className="nav nav-pills flex-column flex-sm-row">
        <a
          onClick={onClickSubTab.bind(this, 1)}
          className={classNames(
            'flex-sm-fill text-sm-center nav-link cursor-pointer',
            {
              'bg-light': subTabIndex === 1,
            },
          )}
        >
          {translatedFields.config.email.tencentCloud}
        </a>
        <a
          onClick={onClickSubTab.bind(this, 2)}
          className={classNames(
            'flex-sm-fill text-sm-center nav-link cursor-pointer',
            {
              'bg-light': subTabIndex === 2,
            },
          )}
        >
          {translatedFields.config.email.aliCloud}
        </a>
      </nav>

      {subTabIndex === 1 && (
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div className="row">
            <div className="col">
              <ImageItem
                form={form}
                onChangeForm={onChangeForm}
                translatedFields={translatedFields}
              />
            </div>
            <div className="col">
              <div className="vstack gap-4">
                <div>
                  <label className="form-label">
                    {translatedFields.config.email.secretId}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="secretId"
                    value={form.tencent.secretId}
                    onChange={onChangeForm}
                    aria-describedby="secretId"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.secretKey}
                  </label>
                  <input
                    type="password"
                    autoComplete="password"
                    className="form-control"
                    name="secretKey"
                    value={form.tencent.secretKey}
                    onChange={onChangeForm}
                    aria-describedby="secretKey"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.region}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="region"
                    value={form.tencent.region}
                    onChange={onChangeForm}
                    aria-describedby="region"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.fromEmailAddress}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="fromEmailAddress"
                    value={form.tencent.fromEmailAddress}
                    onChange={onChangeForm}
                    aria-describedby="fromEmailAddress"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.subject}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="subject"
                    value={form.tencent.subject}
                    onChange={onChangeForm}
                    aria-describedby="subject"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.replyToAddresses}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="replyToAddresses"
                    value={form.tencent.replyToAddresses}
                    onChange={onChangeForm}
                    aria-describedby="replyToAddresses"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.templateId}
                  </label>
                  <input
                    min={1}
                    type="number"
                    className="form-control"
                    name="templateId"
                    value={form.tencent.template.templateId}
                    onChange={onChangeForm}
                    aria-describedby="templateId"
                  />
                </div>
              </div>
            </div>
          </div>

          <button
            type="submit"
            disabled={updateEmailConfigMutation.isLoading || isDisabledSave}
            className="btn btn-success col col-lg-2 my-4"
          >
            {updateEmailConfigMutation.isLoading && <Spinner classs="me-2" />}
            {translatedFields.operate.update}
          </button>
        </form>
      )}

      {subTabIndex === 2 && (
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div className="row">
            <div className="col">
              <ImageItem
                form={form}
                onChangeForm={onChangeForm}
                translatedFields={translatedFields}
              />
            </div>
            <div className="col">
              <div className="vstack gap-4">
                <div>
                  <label className="form-label">
                    {translatedFields.config.email.accessKeyId}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="accessKeyId"
                    value={form.aliyun.accessKeyId}
                    onChange={onChangeForm}
                    aria-describedby="accessKeyId"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.accessKeySecret}
                  </label>
                  <input
                    type="password"
                    autoComplete="password"
                    className="form-control"
                    name="accessKeySecret"
                    value={form.aliyun.accessKeySecret}
                    onChange={onChangeForm}
                    aria-describedby="accessKeySecret"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.accountName}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="accountName"
                    value={form.aliyun.accountName}
                    onChange={onChangeForm}
                    aria-describedby="accountName"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.subject}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="subject"
                    value={form.aliyun.subject}
                    onChange={onChangeForm}
                    aria-describedby="subject"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.fromAlias}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="fromAlias"
                    value={form.aliyun.fromAlias}
                    onChange={onChangeForm}
                    aria-describedby="fromAlias"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.htmlBody}
                  </label>
                  <textarea
                    rows={6}
                    className="form-control"
                    name="htmlBody"
                    value={form.aliyun.htmlBody}
                    onChange={onChangeForm}
                    aria-describedby="htmlBody"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.tagName}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="tagName"
                    value={form.aliyun.tagName}
                    onChange={onChangeForm}
                    aria-describedby="tagName"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.replyAddress}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="replyAddress"
                    value={form.aliyun.replyAddress}
                    onChange={onChangeForm}
                    aria-describedby="replyAddress"
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.config.email.replyAddressAlias}
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="replyAddressAlias"
                    value={form.aliyun.replyAddressAlias}
                    onChange={onChangeForm}
                    aria-describedby="replyAddressAlias"
                  />
                </div>
              </div>
            </div>
          </div>

          <button
            type="submit"
            disabled={updateEmailConfigMutation.isLoading || isDisabledSave}
            className="btn btn-success col col-lg-2 my-4"
          >
            {updateEmailConfigMutation.isLoading && <Spinner classs="me-2" />}
            {translatedFields.operate.update}
          </button>
        </form>
      )}
    </div>
  );
};

const ImageItem = ({
  form,
  translatedFields,
  onChangeForm,
}: {
  form: IConfigEmailItem;
  onChangeForm(
    e: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
  ): void;
  translatedFields: PrefixedTTranslatedFields<'configAdminPage'>;
}) => {
  return (
    <div className="vstack gap-4">
      <div>
        <label className="form-label">
          {translatedFields.config.phone.serviceProvider}
        </label>
        <select
          name="service"
          value={form.service}
          onChange={onChangeForm}
          className="form-select"
          aria-label="service"
        >
          <option value="TENCENT">
            {translatedFields.config.phone.tencentCloud}
          </option>
          <option value="ALIYUN">
            {translatedFields.config.phone.aliCloud}
          </option>
        </select>
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.enable}
        </label>
        <select
          name="enable"
          value={form.tencent.enable + ''}
          onChange={onChangeForm}
          className="form-select"
          aria-label="enable"
        >
          <option value="true">true</option>
          <option value="false">false</option>
        </select>
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.expire}
        </label>
        <input
          type="text"
          className="form-control"
          name="expire"
          value={form.tencent.expire}
          onChange={onChangeForm}
          aria-describedby="expire"
        />
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.total}
        </label>
        <input
          min={1}
          type="number"
          className="form-control"
          name="total"
          value={form.tencent.total}
          onChange={onChangeForm}
          aria-describedby="total"
        />
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.interval}
        </label>
        <input
          type="text"
          className="form-control"
          name="interval"
          value={form.tencent.interval}
          onChange={onChangeForm}
          aria-describedby="interval"
        />
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.recoveryTime}
        </label>
        <input
          type="text"
          className="form-control"
          name="recoveryTime"
          value={form.tencent.recoveryTime}
          onChange={onChangeForm}
          aria-describedby="recoveryTime"
        />
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.length}
        </label>
        <input
          min={1}
          type="number"
          className="form-control"
          name="length"
          value={form.tencent.length}
          onChange={onChangeForm}
          aria-describedby="length"
        />
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.alphanumeric}
        </label>
        <select
          name="alphanumeric"
          value={form.tencent.alphanumeric + ''}
          onChange={onChangeForm}
          className="form-select"
          aria-label="alphanumeric"
        >
          <option value="true">true</option>
          <option value="false">false</option>
        </select>
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.alphabetic}
        </label>
        <select
          name="alphabetic"
          value={form.tencent.alphabetic + ''}
          onChange={onChangeForm}
          className="form-select"
          aria-label="alphabetic"
        >
          <option value="true">true</option>
          <option value="false">false</option>
        </select>
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.ascii}
        </label>
        <select
          name="ascii"
          value={form.tencent.ascii + ''}
          onChange={onChangeForm}
          className="form-select"
          aria-label="ascii"
        >
          <option value="true">true</option>
          <option value="false">false</option>
        </select>
      </div>

      <div>
        <label className="form-label">
          {translatedFields.config.phone.numeric}
        </label>
        <select
          name="numeric"
          value={form.tencent.numeric + ''}
          onChange={onChangeForm}
          className="form-select"
          aria-label="numeric"
        >
          <option value="true">true</option>
          <option value="false">false</option>
        </select>
      </div>
    </div>
  );
};
